package org.insightech.er.editor.model.dbexport.excel.sheet_generator;

import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.insightech.er.editor.model.ERDiagram;
import org.insightech.er.editor.model.ObjectModel;
import org.insightech.er.editor.model.dbexport.excel.ExportToExcelManager.LoopDefinition;
import org.insightech.er.editor.model.diagram_contents.not_element.trigger.Trigger;
import org.insightech.er.editor.model.progress_monitor.ProgressMonitor;
import org.insightech.er.util.POIUtils;

public class TriggerSheetGenerator extends AbstractSheetGenerator {

    private static final String KEYWORD_TRIGGER_NAME = "$PTGN";

    private static final String KEYWORD_TRIGGER_DESCRIPTION = "$TGDSC";

    private static final String KEYWORD_TRIGGER_SQL = "$SQL";

    public void setTriggerData(final HSSFWorkbook workbook, final HSSFSheet sheet, final Trigger trigger) {
        POIUtils.replace(sheet, KEYWORD_TRIGGER_NAME, getValue(keywordsValueMap, KEYWORD_TRIGGER_NAME, trigger.getName()));

        POIUtils.replace(sheet, KEYWORD_TRIGGER_DESCRIPTION, getValue(keywordsValueMap, KEYWORD_TRIGGER_DESCRIPTION, trigger.getDescription()));

        POIUtils.replace(sheet, KEYWORD_TRIGGER_SQL, getValue(keywordsValueMap, KEYWORD_TRIGGER_SQL, trigger.getSql()));
    }

    @Override
    public void generate(final ProgressMonitor monitor, final HSSFWorkbook workbook, final int sheetNo, final boolean useLogicalNameAsSheetName, final Map<String, Integer> sheetNameMap, final Map<String, ObjectModel> sheetObjectMap, final ERDiagram diagram, final Map<String, LoopDefinition> loopDefinitionMap) throws InterruptedException {

        for (final Trigger trigger : diagram.getDiagramContents().getTriggerSet()) {
            final String name = trigger.getName();
            final HSSFSheet newSheet = createNewSheet(workbook, sheetNo, name, sheetNameMap);

            final String sheetName = workbook.getSheetName(workbook.getSheetIndex(newSheet));
            monitor.subTaskWithCounter("[Trigger] " + sheetName);

            sheetObjectMap.put(sheetName, trigger);

            setTriggerData(workbook, newSheet, trigger);
            monitor.worked(1);
        }
    }

    @Override
    public String getTemplateSheetName() {
        return "trigger_template";
    }

    @Override
    public String[] getKeywords() {
        return new String[] {KEYWORD_TRIGGER_NAME, KEYWORD_TRIGGER_DESCRIPTION, KEYWORD_TRIGGER_SQL};
    }

    @Override
    public int getKeywordsColumnNo() {
        return 16;
    }

    @Override
    public int count(final ERDiagram diagram) {
        return diagram.getDiagramContents().getTriggerSet().getObjectList().size();
    }

}
